package com.ruoyi.gis.controller;

import java.io.UnsupportedEncodingException;
import java.net.MalformedURLException;
import java.util.Comparator;
import java.util.List;
import java.util.stream.Collectors;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.alibaba.fastjson2.JSONObject;
import com.ruoyi.common.core.domain.entity.SysDictData;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.framework.web.service.TokenService;
import com.ruoyi.gis.geoserver.service.GeoserverService;
import com.ruoyi.gis.domain.GisLayerBase;
import com.ruoyi.gis.domain.ImportLayerVo;
import com.ruoyi.gis.service.IGisLayerBaseService;
import com.ruoyi.gis.vo.RasterStyleConfig;
import com.ruoyi.system.service.ISysDictTypeService;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.gis.domain.GisLayer;
import com.ruoyi.gis.service.IGisLayerService;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;

/**
 * 图层管理Controller
 *
 * @author rww
 * @date 2023-02-27
 */
@RestController
@RequestMapping("/gis/layer")
public class GisLayerController extends BaseController
{
    @Autowired
    private IGisLayerService gisLayerService;

    @Autowired
    private GeoserverService geoserverService;
    @Autowired
    private TokenService tokenService;

    @Autowired
    private ISysDictTypeService dictTypeService;

    @Autowired
    private IGisLayerBaseService gisLayerBaseService;

    /**
     * 查询图层管理列表
     */
//    @PreAuthorize("@ss.hasPermi('gis:layer:list')")
    @GetMapping("/list")
    public TableDataInfo list(HttpServletRequest request,GisLayer gisLayer)
    {
        startPage();
        LoginUser loginUser = tokenService.getLoginUser(request);
        gisLayer.setUserId(loginUser.getUserId());
        List<GisLayer> list = gisLayerService.selectGisLayerList(gisLayer);
        return getDataTable(list);
    }

//    @PreAuthorize("@ss.hasPermi('gis:layer:list')")
    @GetMapping("/list/all/group")
    public AjaxResult listAllGroup(HttpServletRequest request,GisLayer gisLayer)
    {
        gisLayer.setGroup(GisLayer.type_group);
        LoginUser loginUser = tokenService.getLoginUser(request);
        gisLayer.setUserId(loginUser.getUserId());
        List<GisLayer> list = gisLayerService.selectGisLayerList(gisLayer);
        return AjaxResult.success(list);
    }

//    @PreAuthorize("@ss.hasPermi('gis:layer:list')")
    @GetMapping("/list/all/layer")
    public AjaxResult listAllLayer(HttpServletRequest request,GisLayer gisLayer)
    {
        LoginUser loginUser = tokenService.getLoginUser(request);
        gisLayer.setUserId(loginUser.getUserId());
        List<GisLayer> list = gisLayerService.selectGisLayerList(gisLayer);
        return AjaxResult.success(list);
    }
    //获取地图底图配置
    @GetMapping("/configs")
    public AjaxResult listGisConfig(HttpServletRequest request,GisLayer gisLayer)
    {
//        LoginUser loginUser = tokenService.getLoginUser(request);
//        gisLayer.setUserId(loginUser.getUserId());
//        List<GisLayer> list = gisLayerService.selectGisLayerList(gisLayer);
        JSONObject data = new JSONObject();
        List<SysDictData> mapTokens = dictTypeService.selectDictDataByType("map_tokens");
        JSONObject tokens = new JSONObject();
        mapTokens.forEach(item->{
            tokens.put(item.getDictLabel(),item.getDictValue());
        });
        data.put("tokens",tokens);
        List<GisLayerBase> gisLayerBases = gisLayerBaseService.
                selectGisLayerBaseList(new GisLayerBase());
        data.put("defaultBaseMap","tianditu");
        data.put("defaultBaseMapType","image");
        data.put("baseLayers",gisLayerBases.stream()
                .filter(i->"10".equals(i.getLoad()))
                .sorted(Comparator.comparing(GisLayerBase::getSort))
                .collect(Collectors.toList()));
        data.put("mapLayers",gisLayerBases.stream()
                .filter(i->"20".equals(i.getLoad()))
                .sorted(Comparator.comparing(GisLayerBase::getSort))
                .collect(Collectors.toList()));
        return AjaxResult.success(data);
    }

    /**
     * 导出图层管理列表
     */
    @PreAuthorize("@ss.hasPermi('gis:layer:export')")
    @Log(title = "图层管理", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, GisLayer gisLayer)
    {
        List<GisLayer> list = gisLayerService.selectGisLayerList(gisLayer);
        ExcelUtil<GisLayer> util = new ExcelUtil<GisLayer>(GisLayer.class);
        util.exportExcel(response, list, "图层管理数据");
    }

    /**
     * 获取图层管理详细信息
     */
//    @PreAuthorize("@ss.hasPermi('gis:layer:query')")
    @GetMapping(value = "/{layerId}")
    public AjaxResult getInfo(@PathVariable("layerId") Long layerId)
    {
        return success(gisLayerService.selectGisLayerByLayerId(layerId));
    }



    /**
     * 新增图层管理
     */
    @PreAuthorize("@ss.hasPermi('gis:layer:add')")
    @Log(title = "图层管理", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(HttpServletRequest request, @RequestBody GisLayer gisLayer)
    {
        LoginUser loginUser = tokenService.getLoginUser(request);
        gisLayer.setUserId(loginUser.getUserId());
        return toAjax(gisLayerService.insertGisLayer(gisLayer));
    }


    @PreAuthorize("@ss.hasPermi('gis:layer:add')")
    @Log(title = "图层管理", businessType = BusinessType.INSERT)
    @PostMapping("/addtop")
    public AjaxResult addTop(HttpServletRequest request, @RequestBody GisLayer gisLayer)
    {
        gisLayer.setGroup(GisLayer.type_group);
        gisLayer.setLayerName(gisLayer.getLayerTitle());
        gisLayer.setLayerTitle(gisLayer.getLayerTitle());
        LoginUser loginUser = tokenService.getLoginUser(request);
        gisLayer.setUserId(loginUser.getUserId());
        return toAjax(gisLayerService.insertGisLayer(gisLayer));
    }


    @PostMapping("/import/geoserver/layer")
    public AjaxResult importGeroserverLayer(HttpServletRequest request, @RequestBody ImportLayerVo importLayerVo)
    {
        LoginUser loginUser = tokenService.getLoginUser(request);
        gisLayerService.importGeoserverLayer(importLayerVo,loginUser);
        return AjaxResult.success();
    }

    /**
     * 修改图层管理
     */
//    @PreAuthorize("@ss.hasPermi('gis:layer:edit')")
    @Log(title = "图层管理", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody GisLayer gisLayer)
    {
        return toAjax(gisLayerService.updateGisLayer(gisLayer));
    }

//    @PreAuthorize("@ss.hasPermi('gis:layer:edit')")
    @Log(title = "图层管理", businessType = BusinessType.UPDATE)
    @PutMapping("/formate")
    public AjaxResult editFormate(@RequestBody GisLayer gisLayer) throws MalformedURLException, UnsupportedEncodingException {
        gisLayerService.updateGisLayer(gisLayer);
//        String sourceFormat = "application/vnd.mapbox-vector-tile";
        geoserverService.updateLayerTitleCache(gisLayer.getWorkspace(),
                gisLayer.getLayerName(), gisLayer.getSourceFormat());
        return AjaxResult.success("修改成功");
    }

    //跟新栅格图层样式
    @PostMapping(value = "/rasterStyle/{layerId}")
    public AjaxResult setRasterStyle(@PathVariable("layerId") Long layerId,
                                     @RequestBody RasterStyleConfig config)
    {
        GisLayer gisLayer = gisLayerService.selectGisLayerByLayerId(layerId);
        gisLayerService.updateRasterLayerStyle(gisLayer,config);
        return success(gisLayer);
    }

    /**
     * 删除图层管理
     */
    @PreAuthorize("@ss.hasPermi('gis:layer:remove')")
    @Log(title = "图层管理", businessType = BusinessType.DELETE)
	@DeleteMapping("/{layerId}")
    public AjaxResult remove(@PathVariable Long layerId)
    {
        if (gisLayerService.hasChildByLayerId(layerId))
        {
            return warn("存在下级图层,不允许删除");
        }
        return toAjax(gisLayerService.deleteGisLayerByLayerId(layerId));
    }
}
